import React, { ChangeEvent, useEffect, useState } from "react";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { Input } from "antd";
import { LIST_SEARCH_PARAM_KEY } from "../../constants";
import styles from "./ListSearch.module.scss";

const { Search } = Input;

const ListSearch: React.FC = () => {
  const [value, setValue] = useState("");

  const nav = useNavigate();
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
    setValue(curVal);
  }, [searchParams]);

  function handlerSearch(value: string) {
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value}`,
    });
  }

  function handlerChange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value);
  }

  return (
    <Search
      className={styles.search}
      placeholder="请输入问卷标题"
      value={value}
      onSearch={handlerSearch}
      onChange={handlerChange}
      size="large"
      allowClear
    />
  );
};

export default ListSearch;
